<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/extras/importer/gzip_importer.html">
<link rel="import" href="/tracing/extras/importer/jszip.html">
<link rel="import" href="/tracing/importer/importer.html">
<link rel="import" href="/tracing/model/model.html">

<script>
'use strict';

/**
 * @fileoverview ZipImporter inflates zip compressed data and passes it along
 * to an actual importer.
 */
tr.exportTo('tr.e.importer', function() {
  function ZipImporter(model, eventData) {
    if (eventData instanceof ArrayBuffer) {
      eventData = new Uint8Array(eventData);
    }
    this.model_ = model;
    this.eventData_ = eventData;
  }

  /**
   * @param {eventData} string Possibly zip compressed data.
   * @return {boolean} Whether eventData looks like zip compressed data.
   */
  ZipImporter.canImport = function(eventData) {
    let header;
    if (eventData instanceof ArrayBuffer) {
      header = new Uint8Array(eventData.slice(0, 2));
    } else if (typeof(eventData) === 'string' || eventData instanceof String) {
      header = [eventData.charCodeAt(0), eventData.charCodeAt(1)];
    } else {
      return false;
    }
    return header[0] === 'P'.charCodeAt(0) && header[1] === 'K'.charCodeAt(0);
  };

  ZipImporter.prototype = {
    __proto__: tr.importer.Importer.prototype,

    get importerName() {
      return 'ZipImporter';
    },

    isTraceDataContainer() {
      return true;
    },

    extractSubtraces() {
      const zip = new JSZip(this.eventData_);
      const subtraces = [];
      for (const idx in zip.files) {
        subtraces.push(zip.files[idx].asBinary());
      }
      return subtraces;
    }
  };

  tr.importer.Importer.register(ZipImporter);

  return {
    ZipImporter,
  };
});
</script>
